package com.zcj.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcj.common.utils.PageUtils;
import com.zcj.common.utils.Query;

import com.zcj.gulimall.product.dao.CategoryDao;
import com.zcj.gulimall.product.entity.CategoryEntity;
import com.zcj.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询商品分类表
     * @return
     */
    @Override
    public List<CategoryEntity> listTree() {
        //查询所以数据
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        //设置层级关系
        //一级分类
        List<CategoryEntity> levelOne = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu)->{
                    menu.setChildren(getChildren(menu,categoryEntityList));
                    return menu;
                })
                .sorted((menu1,menu2)->{
                    return (menu1.getSort() == null ? 0 :menu1.getSort()) - (menu2.getSort() == null ? 0 :menu2.getSort());
                })
                .collect(Collectors.toList());
        return levelOne;
    }

    @Override
    public void removeMenuByIds(List<Long> list) {
        //TODO: 1、检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(list);
    }

    /**
     *  递归查找所有菜单的子菜单
     * @param root 当前菜单
     * @param all   所有菜单
     * @return 子级菜单
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> childList =  all.stream().filter(categoryEntity ->{
            return categoryEntity.getParentCid().equals(root.getCatId());
        })
        .map(entity -> {
            entity.setChildren(getChildren(entity,all));
            return entity;
        })
         .sorted((menu1,menu2)->{
            return (menu1.getSort() == null ? 0 :menu1.getSort()) - (menu2.getSort() == null ? 0 :menu2.getSort());
         })
        .collect(Collectors.toList());
        return childList;
    }
}